/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import javax.inject.Inject;

import ru.irenproject.it.ItOutput;
import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Event;
import ru.irenproject.store.Stash;
import ru.irenproject.store.Thing;

import com.google.protobuf.ByteString;
import com.google.protobuf.Message;

public final class ProfileViewer extends AbstractThing implements Visual {
  public static ProfileViewer create(Profile profile) {
    ProfileViewer res = profile.store().create(ProfileViewer.class);
    res.prepare(profile);
    return res;
  }

  @Stash private UiProtos.ProfileViewer.Builder $;
  private final ItOutput fItOutput;

  @Inject ProfileViewer(ItOutput itOutput) {
    fItOutput = itOutput;
  }

  private void prepare(Profile profile) {
    setProfile(profile);
  }

  public Profile profile() {
    return get($.getProfile(), Profile.class);
  }

  public void setProfile(Profile profile) {
    $.setProfile(profile.id());
    profile.addListener(this);
    markForRender();
  }

  @Override public Message render() {
    return UiProtos.ProfileViewerShape.newBuilder()
        .setItStream(ByteString.copyFrom(fItOutput.profileToBytes(profile())))
        .build();
  }

  @Override protected void handleEvent(Event e, Thing source) {
    if ((e instanceof Profile.ChangeEvent) && (source == profile())) {
      markForRender();
    }
  }
}
